/*
 * Copyright (C) 2014 Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.bambole.controller;

import com.googlecode.bambole.domain.Status;
import com.googlecode.bambole.controller.util.JsfUtil;
import com.googlecode.bambole.controller.util.PaginationUtil;
import com.googlecode.bambole.domain.User;
import com.googlecode.bambole.facade.StatusFacade;
import com.googlecode.bambole.util.EntryFormatUtil;
import com.googlecode.bambole.util.SearchUtil;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

/**
 *
 * @author Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 */
@Named("statusController")
@SessionScoped
public class StatusController implements Serializable {

    private Status current;
    private DataModel items = null;

    @EJB
    private com.googlecode.bambole.facade.StatusFacade ejbFacade;

    private PaginationUtil pagination;
    private String query;
    private String openingSearch;
    private String closingSearch;
    private int selectedItemIndex;
    private int recordCount;

    public StatusController() {
    }

    public Status getSelected() {
        if (current == null) {
            current = new Status();
        }
        return current;
    }

    public void setSelected(Status current) {
        this.current = current;
    }

    private StatusFacade getFacade() {
        return ejbFacade;
    }

    public boolean isPaginationFromSearch() {
        return !getQuery().equals(getDefaultQuery());
    }

    public PaginationUtil getPagination() {
        if (pagination == null) {
            pagination = new PaginationUtil(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count(getQuery());
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, getQuery()));
                }
            };
        }
        return pagination;
    }

    public String refreshList() {
        query = null;
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareList() {
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareView() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        recordCount = getFacade().count(getQuery());

        return "view.xhtml?faces-redirect=true";
    }

    public String prepareCreate() {
        current = new Status();
        return "create.xhtml?faces-redirect=true";
    }

    public String create() {

        if (!validateRecord()) {
            return null;
        }

        Date date = new Date();
        User user = (User) JsfUtil.getSessionParameter("user");
        current.setCreated(date);
        current.setCreatedBy(user);
        current.setUpdated(date);
        current.setUpdatedBy(user);

        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String prepareEdit() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));

            return null;
        }
        return "edit.xhtml?faces-redirect=true";
    }

    public String update() {

        if (!validateRecord()) {
            return null;
        }

        current.setUpdated(new Date());
        current.setUpdatedBy((User) JsfUtil.getSessionParameter("user"));

        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String destroy() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }
        performDestroy();
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public Status getStatus(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    public void setSelectedItemIndex(int selectedItemIndex) {
        this.selectedItemIndex = selectedItemIndex + pagination.getPageFirstItem();
    }

    public boolean isHasNextRecord() {
        return selectedItemIndex + 2 <= recordCount;
    }

    public boolean isHasPreviousRecord() {
        return selectedItemIndex > 0;
    }

    public String nextItem() {

        selectedItemIndex++;

        if (selectedItemIndex < recordCount) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    public String previousItem() {

        selectedItemIndex--;

        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    private boolean validateRecord() {

        boolean retVal = true;

        if (!getFacade().isNameUnique(current.getName(), current.getId() == null ? -1 : current.getId())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NameAlreadyExists"));

            retVal = false;
        }

        if (!EntryFormatUtil.isStatusSequenceValid(current.getSequence())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidSequence"));

            retVal = false;
        }

        if (!getFacade().isSequenceUnique(current.getSequence(), current.getId() == null ? -1 : current.getId())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("SequenceAlreadyExists"));

            retVal = false;
        }

        if (!current.isEnabled() && (current.isOpening() || current.isClosing())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("OpeningOrClosingRecordCannotBeDisabled"));

            retVal = false;
        }

        if (current.isOpening() && current.isClosing()) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordCannotBeOpeningAndClosingSimultaneously"));

            retVal = false;
        }

        if (current.isOpening()) {
            if (!getFacade().isOpeningOptionUnique(current.getId() == null ? -1 : current.getId())) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("OpeningRecordAlreadyExists"));

                retVal = false;
            }
        } else {
            if (!getFacade().isOpeningOptionSet(current.getId() == null ? -1 : current.getId())) {
                JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("OpeningRecordNotSet"));
            }
        }

        if (!current.isClosing() && !getFacade().isClosingOptionSet(current.getId() == null ? -1 : current.getId())) {
            JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("ClosingRecordNotSet"));
        }

        return retVal;
    }

    private String getQuery() {
        return query == null ? getDefaultQuery() : query;
    }

    private String getDefaultQuery() {
        return "SELECT s FROM Status s";
    }

    public String prepareSearch() {

        current = new Status();

        openingSearch = null;

        closingSearch = null;

        return "search.xhtml?faces-redirect=true";
    }

    public String performSearch() {

        boolean queryAddAnd = false;

        boolean queryContainsErrors = false;

        query = getDefaultQuery();

        if ((current.getName() != null && !current.getName().isEmpty())
                || (current.getDescription() != null && !current.getDescription().isEmpty())
                || (getOpeningSearch() != null && !getOpeningSearch().isEmpty())
                || (getClosingSearch() != null && !getClosingSearch().isEmpty())
                || (current.getSequence() != null && !current.getSequence().isEmpty())) {

            query = query + " WHERE ";

            if (current.getName() != null && !current.getName().isEmpty()) {
                queryAddAnd = true;
                query = query + "s.name LIKE \'%" + current.getName() + "%\'";
            }

            if (current.getDescription() != null && !current.getDescription().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "s.description LIKE \'%" + current.getDescription() + "%\'";
            }

            if (getOpeningSearch() != null && !getOpeningSearch().isEmpty()) {
                String openingSearchClause = SearchUtil.getQueryClause("s.opening", getOpeningSearch(), 'b', queryAddAnd);
                if (!openingSearchClause.equals("*")) {
                    query = query + openingSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getClosingSearch() != null && !getClosingSearch().isEmpty()) {
                String closingSearchClause = SearchUtil.getQueryClause("s.closing", getClosingSearch(), 'b', queryAddAnd);
                if (!closingSearchClause.equals("*")) {
                    query = query + closingSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (current.getSequence() != null && !current.getSequence().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                }
                query = query + "s.sequence LIKE \'%" + current.getSequence() + "%\'";
            }
        }

        if (queryContainsErrors) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidSearchCriteria"));

            return prepareSearch();
        } else {
            recreatePagination();
            recreateModel();

            return "list.xhtml?faces-redirect=true";
        }
    }

    public Status getOpeningStatus() {
        return getFacade().getOpeningStatus();
    }

    public SelectItem[] getItemsAvailableSelectOne(boolean includeDisabledItems) {

        List<Status> statusList;

        if (includeDisabledItems) {
            statusList = getFacade().findAll();
        } else {
            statusList = getFacade().findEnabled();
        }

        SelectItem[] statuses = new SelectItem[statusList.size() + 1];

        statuses[0] = new SelectItem(null, null);

        int i = 1;
        for (Status status : statusList) {
            statuses[i++] = new SelectItem(status, status.getNameWithDisabledFormatting());
        }

        return statuses;
    }

    public String getOpeningSearch() {
        return openingSearch;
    }

    public void setOpeningSearch(String openingSearch) {
        this.openingSearch = openingSearch;
    }

    public String getClosingSearch() {
        return closingSearch;
    }

    public void setClosingSearch(String closingSearch) {
        this.closingSearch = closingSearch;
    }
}
